import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:gd_assistant/globalConfig.dart';
import 'package:gd_assistant/page/public/colors.dart';
import 'package:gd_assistant/page/public/themeUtils.dart';
import 'package:gd_assistant/util/customRoute.dart';
import 'package:gd_assistant/util/dataUtil.dart';
import 'package:gd_assistant/util/eventBus.dart';
import 'package:gd_assistant/util/publicUtil.dart';
import 'package:gd_assistant/page/public/publicView.dart';
import 'package:image_pickers/image_pickers.dart';
import 'package:gd_assistant/api/apiHandler.dart';

class changeMinePage extends StatefulWidget {
  @override
  _changeMinePageState createState() => _changeMinePageState();
}

class _changeMinePageState extends State<changeMinePage> {
  bool isDark = false;
  final _bottomSheetScaffoldKey = GlobalKey<ScaffoldState>();
  var _imgPath;
  final titles = ["拍照","从相册选择"];
  String nickName = "";
  String avatar = "";
  String phone = "";

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    loadData();
  }

  @override
  void dispose() {
    super.dispose();
  }

  loadData() async {
    nickName = dataUtil.getValue(dataUtil.nickNameKey);
    avatar = dataUtil.getValue(dataUtil.assistantAvatarKey);
    phone = dataUtil.getValue(dataUtil.assistantPhoneKey);
    setState(() {});
  }
  
  Future<void> selectImages() async {
    try {
      List<Media> newList = await ImagePickers.pickerPaths(
          galleryMode: GalleryMode.image,
          selectCount: 1,
          showCamera: true,
          compressSize: 500,
          uiConfig: UIConfig(uiThemeColor: isDark ? Colours.dark_bg_color : Colors.blue),
          cropConfig: CropConfig(enableCrop: true)
      );
      if (newList.length > 0) {
        TostUtil.showLoading(context, "正在更改头像");
        List<String> result = await publicUtil.onUploadFiles([newList[0].path]);
        if (result.length > 0) {
          await apiHandler.updateAssistantInfo(avatar: result[0]);
          await dataUtil.setValue(dataUtil.assistantAvatarKey, result[0]);
          loadData();
          EventBus().emit("infoChange");
        }
        TostUtil.removeLoading(context);
      }
      
    } on  PlatformException{}
  }

  @override
  Widget build(BuildContext context) {
    isDark = ThemeUtils.isDark(context);
    Color bg_color = isDark ? Colours.dark_bg_gray : Colors.white;
    return Scaffold(
      key: _bottomSheetScaffoldKey,
      appBar: AppBar(
        title: Text("个人信息"),
      ),
      body: Container(
        child: ListView(
          children: <Widget>[
             Padding(
              padding: EdgeInsets.only(top: 20),
              child: GestureDetector(
                onTap: (){
                  //选择拍照
                  selectImages();
                },
                child: Container(
                  height: 100,
                  color: bg_color,
                  child: Padding(
                    padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
                    child:  Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text("头像", style: TextStyle(fontSize: 18)),
                        Row(
                          children: <Widget>[
                            Container(
                              padding: EdgeInsets.only(right: 5),
                              child: Container(
                                child: ClipOval(
                                  child: ExtendedImage.network(
                                    GlobalConfig.qiNiuUri + avatar,
                                    width: 66,
                                    height: 66,
                                  ),
                                ),
                              )
                            ),
                            Icon(Icons.arrow_forward_ios, size: 15, color: Colors.grey),
                          ],
                        )
                      ],
                    ),
                  )
                ),
              )
            ),
             Padding(
              padding: EdgeInsets.only(top: 20),
              child: GestureDetector(
                onTap: (){
                   Navigator.of(context).push(CustomRoute(nameChangePage(name:nickName, onChange: (){loadData();})));
                },
                child: Container(
                  height: 60,
                  color: bg_color,
                  child: Padding(
                    padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
                    child:  Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text("姓名", style: TextStyle(fontSize: 18)),
                        Row(
                          children: <Widget>[
                            Padding(
                              padding: EdgeInsets.only(right: 5),
                              child: Text(nickName, style: TextStyle(fontSize: 16)),
                            ),
                            Icon(Icons.arrow_forward_ios, size: 15, color: Colors.grey),
                          ],
                        )
                      ],
                    ),
                  )
                ),
              )
            ),
            Padding(
              padding: EdgeInsets.only(top: 0),
              child: Container(
                height: 60,
                color: bg_color,
                child: Padding(
                  padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
                  child:  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text("手机号", style: TextStyle(fontSize: 18)),
                      Text(phone, style: TextStyle(fontSize: 16)),
                    ],
                  ),
                )
              ),
            ),
          ],
        ),
      ),
    );
  }
}


class nameChangePage extends StatefulWidget {
  nameChangePage({Key key, this.name: "", this.onChange}):super(key : key);
  String name;
  Function onChange;
  @override
  _nameChangePageState createState() => _nameChangePageState();
}

class _nameChangePageState extends State<nameChangePage> {
  TextEditingController nameC = TextEditingController();
  
  @override
  void initState() {
    super.initState();
    nameC.text = widget.name;
    nameC.addListener(() { setState(() {});});
  }

  updatePatientInfo() async {
    TostUtil.showLoading(context, "姓名保存中...");
    dynamic cb = await apiHandler.updateAssistantInfo(nick_name: nameC.text);
    TostUtil.removeLoading(context);
    if (cb != null) {
      dataUtil.setValue(dataUtil.nickNameKey, nameC.text);
      TostUtil.show("保存成功");
      EventBus().emit("infoChange",{});
    }
    if (widget.onChange != null) {
      widget.onChange();
    }
    Navigator.of(context).pop();
  }

  @override
  void dispose() {
    super.dispose();
    nameC.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("姓名"),
      ),
      body: Container(
        child: ListView(
          children: <Widget>[
            Padding(
              padding: EdgeInsets.only(top: 20),
            ),
            ZLTextField(
              title: "姓名",
              controller: nameC,
              pliceHorder: "请输入名字",
            ),
            Container(
              padding: EdgeInsets.only(top: 10),
              width: double.infinity,
              child: ZLButton(
                  title: "保存",
                  onTap: nameC.text != "" ? () {
                    updatePatientInfo();
                  } : null
                )
            )
          ],
        ),
      ),
    );
  }
}